namespace AdminSG3L.Domain.Entities;

/// <summary>
/// 权限实体。
/// </summary>
public class AppPermission : EntityBase
{
    /// <summary>
    /// 权限名称，必填。
    /// </summary>
    public string PermissionName { get; private set; }
    
    /// <summary>
    /// 权限编码，可选。
    /// </summary>
    public string? PermissionCode { get; private set; }

    /// <summary>
    /// 父权限ID，用于权限分组和层级结构
    /// </summary>
    public Guid? ParentId { get; private set; }

    /// <summary>
    /// 子权限集合
    /// </summary>
    public ICollection<AppPermission> Children { get; private set; } = [];

    /// <summary>
    /// 拥有该权限的角色集合。
    /// </summary>
    public ICollection<AppRole> Roles { get; private set; } = [];

    /// <summary>
    /// 私有构造函数，仅限工厂方法调用。
    /// </summary>
    /// <param name="permissionName">权限名称。</param>
    /// <param name="permissionCode">权限编码。</param>
    /// <param name="description">描述。</param>
    /// <param name="parentId">父权限ID。</param>
    private AppPermission(string permissionName, string? permissionCode = null, string? description = null, Guid? parentId = null)
    {
        PermissionName = permissionName;
        PermissionCode = permissionCode;
        Description = description;
        ParentId = parentId;
    }

    /// <summary>
    /// 创建 AppPermission 对象的工厂方法。
    /// </summary>
    /// <param name="permissionName">权限名称。</param>
    /// <param name="permissionCode">权限编码。</param>
    /// <param name="description">描述。</param>
    /// <param name="parentId">父权限ID。</param>
    /// <param name="isSystem">是否为系统权限。</param>
    /// <returns>AppPermission 对象。</returns>
    public static AppPermission Create(string permissionName, string? permissionCode = null, string? description = null, Guid? parentId = null, bool isSystem = false)
    {
        var permission = new AppPermission(permissionName, permissionCode, description, parentId);
        permission.IsSystem = isSystem;
        return permission;
    }

    public void Update(string permissionName, string? permissionCode, string? description, Guid? parentId = null, bool? isActive = null)
    {
        if (IsSystem)
        {
            throw new InvalidOperationException("系统权限不允许修改");
        }
        PermissionName = permissionName;
        PermissionCode = permissionCode;
        Description = description;
        ParentId = parentId;
        if (isActive.HasValue)
        {
            IsActive = isActive.Value;
        }
        UpdateTime(); // 更新时间戳
    }
}
